<?php

namespace backend\controllers;

use backend\models\UserForm;
use backend\models\Teams;
use backend\models\UserInfo;
use backend\models\UsersTeams;
use common\controllers\BaseController;
use Yii;
use yii\base\ErrorException;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use common\models\User;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\SignupForm;
use yii\helpers\Html;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actions(){
        return [
            'crop'=>[
                'class' => 'common\widgets\avatar\CropAction',
                'config'=>[
                    'bigImageWidth' => '200',     //大图默认宽度
                    'bigImageHeight' => '200',    //大图默认高度
                    'middleImageWidth'=> '100',   //中图默认宽度
                    'middleImageHeight'=> '100',  //中图图默认高度
                    'smallImageWidth' => '50',    //小图默认宽度
                    'smallImageHeight' => '50',   //小图默认高度
                    //头像上传目录（注：目录前不能加"/"）
                    'uploadPath' => 'uploads/news',
                ]
            ]
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserForm();
        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {

        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SignupForm();

        if ($model->load(Yii::$app->request->post()) && $user = $model->signup()) {
            return $this->redirect(['index', 'id' => $user->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $post = Yii::$app->request->post();

        $userInfo = UserInfo::find()->where(['userid' => $id])->one();
        if( !$userInfo ){
            $userInfo = new UserInfo();
        }
        if ($model->load($post) && $model->validate()) {
            if( $userInfo->load($post) ){
                $userInfo->userid = $id;
                $model->save() && $userInfo->save();
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'userInfo' => $userInfo,
            ]);
        }
    }

    public function actionDeleteUser($id){
        $user = $this->findModel($id);
        $user->status = 20;
        $user->save(false);

        return $this->redirect(['index']);


    }



    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * 重置用户密码
     * @param $id
     */
    public function modifyPassword($id)
    {
        $user = $this->findModel($id);
        $user->setPassword('123456');
        $user->save(false);
    }

    public function actionResetPassword($id){
        $pass = Yii::$app->request->post();
        if ($pass){
            $password = $pass['User']['password_hash'];
            $user = $this->findModel($id);
            $user->setPassword($password);
            $user->save(false);
            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }else{
            return $this->render('resetpassword', [
                'model' => $this->findModel($id),
            ]);
        }

    }

    public function actionTeams(){
        $dataProvider = new ActiveDataProvider([
            'query' => Teams::find()->orderBy(['id' => SORT_DESC]),
        ]);

        return $this->render('teams', [
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionCreateTeam(){
        $model = new Teams();

        $teaminfo = Yii::$app->request->post();
        if( $teaminfo ){
            $teaminfo['Teams']['ctime'] = time();
            if ($model->load($teaminfo) && $team = $model->save()) {
                return $this->redirect(['teams', 'id' => $team->id]);
            }
        }

        return $this->render('createteam', [
            'model' => $model,
        ]);
    }

    public function actionUpdateTeam($id){
        $model = Teams::findOne($id);

        $teaminfo = Yii::$app->request->post();
        if( $teaminfo ){
            $teaminfo['Teams']['ctime'] = time();
            if ($model->load($teaminfo) && $team = $model->save()) {
                return $this->redirect(['teams', 'id' => $team->id]);
            }
        }

        return $this->render('createteam', [
            'model' => $model,
        ]);
    }

    public function actionAssignmentTeam(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;

        $model = new Teams();
        if ($model->load($request->post()) && $model->save()) {
            return ['ret' => true];
        } else {
            return ['ret' => false];
        }
    }

    /**
     * 查看组的用户列表
     * @param $id
     * @return string
     */
    public function actionViewTeam($id){
        $team = Teams::findOne($id);
        $dataProvider = new ActiveDataProvider([
            'query' => UsersTeams::find()->alias("ut")
                ->select("ut.id,ut.userid,u.username,ut.teamid,ut.ismanager,t.name as teamname,ut.ctime")
                ->innerJoin("user as u","ut.userid=u.id")
                ->innerJoin("teams as t","t.id=ut.teamid")
                ->where(array('ut.teamid' => $id,'status'=>10))
                ->orderBy(['ut.id' => SORT_DESC]),
        ]);

        return $this->render('usersteams', [
            'dataProvider' => $dataProvider,
            'team' => $team
        ]);
    }

    /**
     * 给组添加用户
     * @param $id
     * @return array
     */
    public function actionAddTeamUser($id){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $user   = Yii::$app->user->identity;
        $request = Yii::$app->request;

        $searchModel = new User();
        if( $request->post() ){
            $userteam = $request->post();

            foreach ($userteam['UsersTeams']['userid'] as $userid){
                $data = array();
                $item['userid'] = $userid;
                $item['teamid'] = $id;
                $item['adminuserid'] = $user->id;
                $item['ctime'] = time();

                $data['UsersTeams'] = $item;

                $exist = UsersTeams::find()->where(array('userid' => $userid,'teamid' => $id))->one();
                if( $exist ){
                    $model = $exist;
                }else{
                    $model = new UsersTeams();
                }

                $model->load($data) && $model->save();
            }

            Yii::$app->session->setFlash('success','Success.');
            $this->redirect('/user/teams');
        }else{
            $model = new UsersTeams();
            return [
                'title' => "add user",
                'content' => $this->renderAjax('_addteamuser', [
                    'model' => $model,
                    'searchModel' => $searchModel,
                ]),
                'footer' => Html::button('close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                    Html::button('save', ['class' => 'btn btn-primary', 'type' => "submit"])
            ];
        }
    }

    public function actionDeleteTeamuser($id){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $delete = UsersTeams::deleteAll(array('id' => $id));

        return ['ret' => $delete];
    }


    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
